package com.jason.apps.dashboard;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Calendar;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.R;
import com.jason.apps.alert.AlertDialogFragment;
import com.jason.apps.alert.EmptyAlert;
import com.jason.apps.alert.ErrorAlert;
import com.jason.apps.notify.EmailValidator;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ParserError")
public class CreateAccount extends SherlockFragment implements OnDateSetListener {
	
	public EditText fname;
	public EditText lname;
	public EditText email;
	public EditText mobile;
	public EditText landline;
	public EditText bday;
	public EditText username;
	public EditText password;
	public EditText filepath;
	public Button register;
	public Button browse;
	public Spinner type;
	public ImageButton cal;
	public TextView txtemail;
	public TextView txtBirthday;
	public TextView txtMobile;
	
	
	String host = "property-portal.uphero.com";
	String ftpuser = "a5596663";
	String ftppass = "ranger123";
	String saveLocation = "/public_html";
	String folderLocation = "/image/";
	
	FTPClient con = null;
	
	SherlockFragmentActivity fa;
	ConsumeWebService consume=new ConsumeWebService();
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.createaccount, container, false);
		fa = (SherlockFragmentActivity) super.getActivity();
		
		 fname=(EditText)view.findViewById(R.id.fname);
		 lname=(EditText)view.findViewById(R.id.lname);
		 email=(EditText)view.findViewById(R.id.email);
		 mobile=(EditText)view.findViewById(R.id.mobile);
		 landline=(EditText)view.findViewById(R.id.landLine);
		 bday=(EditText)view.findViewById(R.id.bday);
		 username=(EditText)view.findViewById(R.id.username);
		 password=(EditText)view.findViewById(R.id.password);
		 filepath=(EditText)view.findViewById(R.id.filepath);
		 register=(Button)view.findViewById(R.id.btnRegister);
		 type=(Spinner)view.findViewById(R.id.spinner1);
		 cal=(ImageButton)view.findViewById(R.id.calendar);
		 browse=(Button)view.findViewById(R.id.browse);
		 txtemail=(TextView)view.findViewById(R.id.validateEmail);
		 txtBirthday=(TextView)view.findViewById(R.id.validateBirthday);
		 txtMobile=(TextView)view.findViewById(R.id.validateMobile);
				 
		 cal.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				 FragmentTransaction ft = getFragmentManager().beginTransaction();
	                SherlockDialogFragment newFragment = new DatePickerDialogFragment(
	                        CreateAccount.this);
	                newFragment.show(ft, "Set Date");
			}
		});

		 register.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if((!fname.getText().toString().trim().equals(""))&&(!lname.getText().toString().trim().equals(""))&&(!email.getText().toString().trim().equals(""))&&(!username.getText().toString().trim().equals(""))&&(!password.getText().toString().trim().equals(""))){
				
				
				/* if(!EmailValidator.validate((email.getText().toString().trim())) && (!EmailValidator.validatePhone(mobile.getText().toString().trim())) && ((bday.getText().toString().trim()).equals(""))){
					txtemail.setText("Invalid Email");
					txtemail.setTextColor(Color.RED);
					txtBirthday.setText("Birthday Required");
					txtBirthday.setTextColor(Color.RED);
					txtMobile.setText("Invalid Number");
					txtMobile.setTextColor(Color.RED);
					
					
				}else if((!EmailValidator.validate((email.getText().toString().trim())) && (!EmailValidator.validatePhone(mobile.getText().toString().trim())))){
					txtemail.setText("Invalid Email");
					txtemail.setTextColor(Color.RED);
					txtMobile.setText("Invalid Number");
					txtMobile.setTextColor(Color.RED);
					
				}else if(!EmailValidator.validate((email.getText().toString().trim())) && ((bday.getText().toString().trim()).equals(""))){
					txtemail.setText("Invalid Email");
					txtemail.setTextColor(Color.RED);
					txtBirthday.setText("Birthday Required");
					txtBirthday.setTextColor(Color.RED);
				}*/
				
				new Create().execute();
				
				}
			
				else{
					FragmentManager fm = getActivity().getSupportFragmentManager();
				     EmptyAlert alert = new EmptyAlert();
				     alert.show(fm, "Alert_Dialog");
				}
			}
		});
	
		
		return view;
    }
	public void setUrl(String file){
		filepath.setText(file);
	}
	private void setDateEditText(int year, int month, int day) {
	       // java.text.DateFormat df = DateFormat.getDateFormat(getActivity());
	        bday.setText(year+"-"+month+"-"+day);
	    }
	//DialogFragment
	public class DatePickerDialogFragment extends SherlockDialogFragment {
        private OnDateSetListener mFragment;

        public DatePickerDialogFragment(OnDateSetListener callback) {
            mFragment = callback;
        }

        public Dialog onCreateDialog(Bundle savedInstanceState) {
            Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int cmonth = c.get(Calendar.MONTH);
            int cday = c.get(Calendar.DAY_OF_MONTH);
            return new DatePickerDialog(getActivity(), mFragment, year, cmonth, cday);
        }
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
       // Date d = new Date(year - 1900, month, day);
        setDateEditText(year,month+1,day);
    }
    public void clearFields(){
    	fname.setText("");
    	lname.setText("");
    	email.setText("");
    	mobile.setText("");
    	landline.setText("");
    	username.setText("");
    	password.setText("");
    	filepath.setText("");
    	username.setText("");
    	password.setText("");
    }


	//Asynctask
	public class Create extends AsyncTask<Void, Void, Void> {

	    private final ProgressDialog dialog = new ProgressDialog(fa);
	    boolean results;

	    protected void onPreExecute() {

	            this.dialog.setMessage("Loading...");
	            this.dialog.show();
	    }


	    protected Void doInBackground(final Void... unused) {

	    	String firstname=fname.getText().toString();
	    	String lastname=lname.getText().toString();
	    	String emailAddress=email.getText().toString();
	    	String mob=mobile.getText().toString();
	    	String land=landline.getText().toString();
	    	String birthday=bday.getText().toString();
	    	String user=username.getText().toString();
	    	String pass=password.getText().toString();
	    	String gettype=type.getSelectedItem().toString();
	    	
	    	String file=filepath.getText().toString();
	    	String filename=new File(file).getName();
	    	
	    	con = new FTPClient();
	    	
			try {
				
					if((filename!=null)){
						
						results = consume.CreateAccount(firstname, lastname, user, pass, emailAddress, mob, land, birthday, gettype, "http://"+host+folderLocation+filename);
						
						Log.v("choya", "nesud"+filename);
						
						if(results){
						con.connect(host);

						if (con.login(ftpuser, ftppass)) {
					
							con.enterLocalPassiveMode(); // important!
							con.setFileType(FTP.BINARY_FILE_TYPE);

							BufferedInputStream buffIn = null;
							buffIn = new BufferedInputStream(
							new FileInputStream(new File(file)),8192);

							boolean result = con.storeFile(saveLocation
							+ folderLocation + filename, buffIn);
							buffIn.close();
							if (result)
								Log.v("upload result", "succeeded");
							con.logout();
							con.disconnect();
							
							
							}
						 
						}						
						
					}
					else{
					results=consume.CreateAccount(firstname, lastname, user, pass, emailAddress, mob, land, birthday, gettype, "");	
					}
					//Toast.makeText(getActivity(), "Created!", Toast.LENGTH_SHORT).show();
				

			} catch (Exception e) {
				Log.e("","",e);
			}
	   
	        return null; 
	    }
	    protected void onPostExecute(Void result) {
	    	if(results){
	    		FragmentManager fm = getActivity().getSupportFragmentManager();
	             AlertDialogFragment alert = new AlertDialogFragment();
	             alert.show(fm, "Alert_Dialog");
	             clearFields();
	    	}
	    	else{
	    		 FragmentManager fm = getActivity().getSupportFragmentManager();
			     ErrorAlert alert = new ErrorAlert();
			     alert.show(fm, "Alert_Dialog");
	    	}
	    	
	    	if (this.dialog!=null) {
	            this.dialog.dismiss();
	            }  
	     }
	  }
}



   
